package kuangstudy;

import java.util.concurrent.locks.ReentrantLock;

/**
 * @author:李雄
 * @create:2022-07-08 17:09
 */
public class TestLock {
    public static void main(String[] args) {

        Ticket ticket = new Ticket();
        Thread thread1= new Thread(ticket);
        Thread thread2 = new Thread(ticket);

        thread1.start();
        thread2.start();

    }
}

class Ticket implements Runnable {
    int ticketNums=10;
    boolean flag=true;
    private ReentrantLock lock = new ReentrantLock();

    @Override
    public void run() {
        while (flag){
            try {
                lock.lock();
                if(ticketNums>0){
                    try {
                        Thread.sleep(100);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                    saleTicket();
                }else {
                    flag=false;
                    return;
                }
            }finally {
                lock.unlock();
            }
        }
    }
    public void saleTicket() {
        System.out.println(ticketNums--);
    }

}

